#include "multiepollserver.h"
#include "epollserver.h"
#include "epolldispatcher.h"
#include "threadpool.h"
#include <iostream>

using namespace std;

string httpRes("HTTP/1.1\r\nStatus:200 ok\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: 37\r\n\r\n{\"errMsg\": \"server internal error 2\"}");

class EchoClientSocket: public EpollClientSocket
{
public:
    EchoClientSocket(int fd): m_fd(fd)
    {
    }
    
    virtual void run()
    {
        Socket socket(m_fd);
        struct timeval timeout;
        timeout.tv_sec = 1;
        timeout.tv_usec = 0;
        socket.setRecvTimeout(timeout);
        socket.setSendTimeout(timeout);
        char buf[1024] = {0};
        int len = 0;
        /// std::cout<<"fd:"<<m_fd<<std::endl;
        /// under EPOLLET mode,the fd is nonblocked 
        while( len != sizeof(buf) )
        {
            len = socket.recvBytes(buf,sizeof(buf));
            if (len < sizeof(buf))
                break;
        }
        
        if (len < 0)
            cout << "recv len:"<<len<<endl;

        socket.sendBytes(httpRes.c_str(),httpRes.length());
    }

private:
    int m_fd;
};

class EchoFactory: public EpollClientFactory
{
public:
    EchoFactory ()
    {}
    
    EchoClientSocket* createClientSocket(int fd)
    {
        return new EchoClientSocket(fd);
    }
};

class ServerMonitor:public Runnable
{
public:
    ServerMonitor(ThreadPool& pool,
            EpollDispatcher& dispatcher,
            EpollServer& server):
    m_pool(pool),
    m_dispatcher(dispatcher),
    m_server(server)
    {
    }
    
    virtual void run()
    {
        while(m_server.running())
        {
            std::cout<<"###############"<<std::endl;
            std::cout<<"closing:"<<m_server.closingFdSize()<<std::endl;
            std::cout<<"queue:"<<m_dispatcher.queueSize()<<std::endl;
            std::cout<<"idle:"<<m_pool.available()<<std::endl;
            std::cout<<"working:"<<m_pool.working()<<std::endl;
            Thread::sleep(2000);
        }
    }
private:
    ThreadPool&               m_pool;
    EpollDispatcher&          m_dispatcher;
    EpollServer&              m_server;
};

int main(int argc, char** argv)
{
    SocketAddress addr("0.0.0.0",7000);
    EchoFactory* factory = new EchoFactory();

    MultiEpollServer server(addr,factory,2,8);

    server.wait(60);
    
    delete factory;
}
    


    
    
    
    
    
    
    
    
    
    
    
    
